<template>
  <!-- 商品管理 -->
  <div class="dashboard-container">
    <SearchTable :show-pagination="false">
      <template slot="header">
        <el-row style="width: 100%">
          <el-input style="width: 300px" @input="searchKeyWord" clearable @clear="onClearKeyWord"
            placeholder="请输入商品名关键词搜索" v-model="condition.product_name"></el-input>
            商品状态：
          <el-select style="margin-left: 12px;" @change="getAllProducts"  v-model="condition.status" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          商品分类：
          <el-select style="margin-left: 12px;" @change="getAllProducts"  v-model="condition.category_id" placeholder="请选择">
            <el-option v-for="item in categoryOptions" :key="item.category_id" :label="item.category_name" :value="item.category_id">
            </el-option>
          </el-select>
        </el-row>
        <el-button type="primary" @click="addStore">新增商品</el-button>
      </template>
      <template>
        <el-table :data="tableData" height="675" border style="width: 100%">
          <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
          <el-table-column prop="product_name" label="商品名称" width="120" align="center"></el-table-column>

          <el-table-column width="120" prop="category_name" label="商品分类" align="center"></el-table-column>
          <el-table-column prop="product_description" label="商品描述" align="center"></el-table-column>
          <el-table-column width="200" prop="pictures" label="商品图片内容" align="center">
            <template v-slot="{ row }">
              <el-carousel v-if="row.pictures && JSON.parse(row.pictures).length > 0" trigger="click" height="150px">
                <el-carousel-item v-for="(item, index) in JSON.parse(row.pictures)" :key="index">
                  <img style="height: 100%" :src="item" @click="showImgDialog(item)" />
                </el-carousel-item>
              </el-carousel>
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column width="120" prop="price" label="价格(元)" align="center"></el-table-column>
          <el-table-column width="120" prop="stock" label="库存(件)" align="center"></el-table-column>
          <el-table-column width="160" prop="created_at" label="发布时间" align="center"></el-table-column>

          <el-table-column prop="status" width="120" label="上架状态" align="center">
            <template v-slot="{ row }">
              <el-tag :type="row.status == 0 ? 'danger' : 'success'">
                {{ row.status == 0 ? "未上架" : "已上架" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" width="160" label="上架状态" align="center">
            <template v-slot="{ row }">
              <el-switch @change="updateStatus(row)" style="display: block" v-model="row.status" active-color="#13ce66"
                inactive-color="#ff4949" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column width="160" label="操作" align="center">
            <template v-slot="{ row }">
              <div class="link-list">
                <el-link :underline="false" type="success" @click="audit(row)">审核</el-link>
                <el-link :underline="false" type="primary" @click="edit(row)">编辑</el-link>
                <el-link :underline="false" type="danger" @click="deleteProducts(row)">删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </SearchTable>

    <!-- 新增商品弹框 -->
    <AddDialog :storeData="storeForm" :title="title" v-if="addVisible" :visible.sync="addVisible"
      @confirm="addStoreConfirm"></AddDialog>

    <!-- 图片 -->
    <el-dialog width="50%" v-if="imgDialogVisible" :visible.sync="imgDialogVisible" title="商品图片">
      <img style="width: 100%" :src="imgDialogData" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SearchTable from "@/components/TableTemplate/SearchTable";
import { getAllProducts, deleteProducts, updateProducts,getAllCategories } from "@/api/user.js";
import AddDialog from "./components/AddDialog";

export default {
  name: "Dashboard",
  components: {
    SearchTable,
    AddDialog,
  },
  data() {
    return {
      options: [
      {
        value: 2,
        label: '全部'
      },  
      {
        value: 0,
        label: '未上架'
      }, {
        value: 1,
        label: '已上架'
      }, 
      ],
      categoryOptions:[],
      keyWord: "",
      productStatus: 2,
      condition: {
        product_name: '',
        category_id: 0,//分类全部
        status: 2
      },
      tableData: [],
      originTableData: [],
      addVisible: false,
      title: "新增商品",
      storeForm: {},
      imgDialogVisible: false,
      imgDialogData: {},

      timer: null,
    };
  },
async  mounted() {
   await this.getAllCategories();
  await  this.getAllProducts();
  },
  computed: {
    ...mapGetters(["name", "token", "role"]),
  },
  methods: {
   async getAllCategories(){
      const res = await getAllCategories();
      this.categoryOptions =[{category_id:0,category_name:'全部'},... res.data];
   
    },
    onClearKeyWord() {

    },
    showImgDialog(item) {
      this.imgDialogVisible = true;
      this.imgDialogData = item;
    },
    deleteProducts(row) {
      this.$confirm(
        "注意：此操作将永久删除该商品，建议使用商品下架功能, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const res = await deleteProducts(row.product_id);
          if (res.status == 0) {
            this.getAllProducts();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message.error("删除失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async updateStatus(row) {
      const params = {
        product_id: row.product_id,
        status: row.status ? 1 : 0,
      };
      const res = await updateProducts(params);
      if (res.status == 0) {
        this.getAllProducts();
        this.$message({
          type: "success",
          message: "操作成功!",
        });
      } else {
        this.$message.error("操作失败！");
      }
    },
    audit(row) {
      this.$confirm("此操作将确认审核通过, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            product_id: row.product_id,
            status: 1,
          };
          const res = await updateProducts(params);
          if (res.status == 0) {
            this.getAllProducts();
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          } else {
            this.$message.error("操作失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    async getAllProducts() {
      const params = {
        product_name: this.condition.product_name,
        category_id: this.condition.category_id,
        status: this.condition.status
      };

     if(params.category_id == 0){//分类全部
      delete params.category_id;
     }
     if(params.status == 2){//上架状态全部
      delete params.status;
     }

      const { data: res } = await getAllProducts(params);
      this.tableData = res || [];
      this.originTableData = res || [];
    },
    searchKeyWord() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(async() => {
        //这里setTimeout用来防抖，也就是500ms内一直在输入，就会清除上次的定时器，就不会一直搜索，等输入完了之后才真正执行一次搜索，优化

      await this.getAllProducts()
 
      }, 500);
    },
    addStore() {
      this.title = "新增商品";
      this.addVisible = true;
      this.storeForm = {};
    },
    edit(row) {
      this.title = "编辑商品";
      this.addVisible = true;
      this.storeForm = row;
    },
    addStoreConfirm() {
      //刷新列表
      this.getAllProducts();
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
}
.link-list {
  .el-link {
    margin: 0 2px;
  }
}

.trainingCourse {
  display: flex;
  flex-wrap: wrap;

  .trainingCourse-card {
    width: 240px;
    margin: 0 10px 20px;
    /* flex: 16%; */
  }

  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }
}
</style>
